/**
 * 
 */
package io.gitee.falllee.dao.util;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

import org.springframework.util.CollectionUtils;

import io.gitee.falllee.dao.enums.SortEnum;
import io.gitee.falllee.dao.model.FormatConstant;

/**
 * @author batty
 * @date 2022-07-01
 *
 */
public class SortPlus {

    private SortPlus() {
    }

    private List<FieldSort> feildSortList;

    public static SortPlus build() {
        return new SortPlus();
    }

    public SortPlus addSort(String field) {
        if (feildSortList == null) {
            feildSortList = new ArrayList<>();
        }
        feildSortList.add(new FieldSort(field));
        return this;
    }

    public SortPlus addSort(String field, SortEnum sort) {
        if (feildSortList == null) {
            feildSortList = new ArrayList<>();
        }
        feildSortList.add(new FieldSort(field).sort(sort));
        return this;
    }

    public String getSort() {
        if (CollectionUtils.isEmpty(feildSortList)) {
            return "";
        }
        StringJoiner sj = new StringJoiner(FormatConstant.COMMA);
        for (FieldSort fieldSort : feildSortList) {
            sj.add(fieldSort.getFieldSort());
        }
        return sj.toString();
    }

    public class FieldSort {

        private String field;

        private SortEnum sort = SortEnum.DEFAULT;

        public FieldSort(String field) {
            this.field = field;
        }

        public FieldSort sort(SortEnum sort) {
            this.sort = sort;
            return this;
        }

        public String getFieldSort() {
            if (SortEnum.DEFAULT.getSort().equals(sort.getSort())) {
                return field;
            }
            return String.format("%s %s", field, sort);
        }
    }
}
